package cn.nawang.ebeim.api.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.nawang.ebeim.api.domain.BackStrategy;
import cn.nawang.ebeim.api.domain.Datasource;
import cn.nawang.ebeim.api.repository.BackStrategyRepository;
import cn.nawang.ebeim.api.service.BackStrategyService;
import cn.nawang.ebeim.api.utils.Util;

/**
 * @ClassName: BackStrategyServiceImpl
 * @Description: TODO
 * @author fanyb
 * @date Aug 24, 2015 5:20:28 PM
 * @version v1.0
 */
@Service("backStrategyService")
public class BackStrategyServiceImpl implements BackStrategyService {

  @Autowired
  private BackStrategyRepository backStrategyRepository;

  @Override
  public BackStrategy getBackStrategy(String datasourceId) {
    return backStrategyRepository.findByDatasourceId(datasourceId);
  }

  @Override
  public BackStrategy findOne(String id) {
    return backStrategyRepository.findOne(id);
  }

  @Override
  public boolean save(BackStrategy backStrategy) {
    try {
      backStrategyRepository.save(backStrategy);
      return true;
    } catch (Exception e) {
      e.printStackTrace();
    }
    return false;
  }

  @Override
  public boolean updateBackStrategy(BackStrategy backStrategy) {
    try {
      BackStrategy backStrategyDb = findOne(backStrategy.getBsId());
      int status = 0;
      if(backStrategy.getBackupTime() != null){
        if(backStrategy.getBackupTime() != backStrategyDb.getBackupTime()){
          status = 1;
        }
      }
      backStrategy = (BackStrategy) Util.comparisonObject(backStrategy, backStrategyDb);
      backStrategy.setBackupTimeStatus(status);
      save(backStrategy);
      return true;
    } catch (Throwable e) {
      e.printStackTrace();
    }
    return false;
  }

  @Override
  public boolean delete(BackStrategy backStrategy) {
    try{
      backStrategyRepository.delete(backStrategy);
      return true;
    }catch(Exception e){
      e.printStackTrace();
    }
    return false;
  }

}
